import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'common/api.dart';

class ForgetPassword extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: MyScaff(),
      decoration: BoxDecoration(
        //设置背景图
        image: DecorationImage(
          image: AssetImage("assets/images/login_bg.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}

class MyScaff extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        //设置向导栏，包括登录和返回字样
        elevation: 0, //将向导栏的阴影设为0，确保全透明
        backgroundColor: Colors.transparent, //将向导栏设为透明颜色
        title: Text(
          "修改密码",
          style: TextStyle(fontSize: 20.0),
        ),
        centerTitle: true,
        leadingWidth: 75.0,
        leading: Padding(
          padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
          child: TextButton(
              style: ButtonStyle(
                  minimumSize: MaterialStateProperty.all(Size(100, 20))),
              onPressed: () {
                passwordsureController.clear(); //在跳转其他页面时清空本页面已经填入的数据
                verificationController.clear();
                newpasswordController.clear();
                phonenumController.clear();
                Navigator.pushNamed(context, '/login');
              },
              child: Text(
                "<返回",
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                ),
              )),
        ),
      ),
      body: SingleChildScrollView(
        //防止页面溢出
        child: MyText(),
      ),
    );
  }
}

//设置字样
class MyText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.center, //容器居中
        child: Column(
          children: [
            //用children同时表示多个字样
            SizedBox(height: 100), //空盒子用于控制距离
            Row(
              mainAxisAlignment: MainAxisAlignment.center, //居中
              children: [
                Text(
                  "欢迎使用Flutter",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 25.0,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            InputNumber(),
            SizedBox(
              height: 20,
            ),
            InputPassword(),
            SizedBox(
              height: 20,
            ),
            SurePassword(),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                VerificationCode(),
                SizedBox(width: 40),
                SendButton(),
              ],
            ),
            SizedBox(
              height: 20,
            ),
            ChangeButton(),
            SizedBox(height: 20),
          ],
        ));
  }
}

TextEditingController passwordsureController = new TextEditingController();
TextEditingController verificationController = new TextEditingController();
TextEditingController newpasswordController = new TextEditingController();
TextEditingController phonenumController = new TextEditingController();

//输入手机号
class InputNumber extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Container(
        width: 300.0,
        alignment: Alignment.center,
        child: TextField(
          inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(11)
                  ], //只允许输入数字
          keyboardType: TextInputType.number,
          controller: phonenumController,
          maxLines: 1,
          decoration: InputDecoration(
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(30),
                borderSide: BorderSide(width: 2, color: Colors.white)),
            labelText: '手机号',
            labelStyle: TextStyle(color: Colors.white),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(30)),
          ),
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}

//输入密码
class InputPassword extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Container(
        width: 300.0,
        alignment: Alignment.center,
        child: TextField(
          controller: newpasswordController,
          maxLines: 1,
          decoration: InputDecoration(
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(30),
                borderSide: BorderSide(width: 2, color: Colors.white)),
            labelText: '新密码',
            labelStyle: TextStyle(color: Colors.white),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(30)),
          ),
          style: TextStyle(color: Colors.white),
          obscureText: true,
        ),
      ),
    );
  }
}

//确认密码
class SurePassword extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Container(
        width: 300.0,
        alignment: Alignment.center,
        child: TextField(
          controller: passwordsureController,
          maxLines: 1,
          decoration: InputDecoration(
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(30),
                borderSide: BorderSide(width: 2, color: Colors.white)),
            labelText: '确认密码',
            labelStyle: TextStyle(color: Colors.white),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(30)),
          ),
          style: TextStyle(color: Colors.white),
          obscureText: true,
        ),
      ),
    );
  }
}

//输入验证码
class VerificationCode extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
        child: Container(
      height: 50.0,
      width: 130.0, //控制容器的宽度
      alignment: Alignment.center,
      child: TextField(
        keyboardType: TextInputType.number,
        controller: verificationController,
        //文本域定义，最大显示一行
        maxLines: 1,
        decoration: InputDecoration(
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide:
                              BorderSide(width: 2, color: Colors.white)),
                      labelText: '验证码',
                      labelStyle: TextStyle(color: Colors.white),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30)),
                    ),
        style: TextStyle(fontSize: 18.0, color: Colors.white),
      ),
    ));
  }
}

String flag;//设一个字符串用于记录随机生成的验证码

//发送验证码按钮
class SendButton extends StatefulWidget {
  //设置为动态的
  SendButton({Key key}) : super(key: key);

  @override
  _SendButtonState createState() => _SendButtonState();
}

class _SendButtonState extends State<SendButton> {
  bool isButtonEnable = true; //确定按钮是否可以按下
  String buttonText = "发送验证码";
  int time = 60;
  Timer timer; //设定计时器
  TextEditingController TimeController = new TextEditingController();

//验证用户是否在数据库内
//setState函数需要在可变组件内使用，故_check函数需要定义在组件内作为内置函数方可使用
  _check(String username, BuildContext context) async {
    var url = Uri.parse(Api.url + '/user/check?username=' + username);
    var response = await http.post(url);
    print('Response body: ${response.body}');
    if (response.body == '1') {      //respons返回1说明用户在数据库中存在，可以进行验证密码和验证码环节
      if (newpasswordController.text.isNotEmpty &&
          passwordsureController.text.isNotEmpty) {
        if (passwordsureController.text != newpasswordController.text)
          Fluttertoast.showToast(msg: '两次输入的密码不一致！');
        else {
          print('点击了发送验证码！');
          print('用户名：' + phonenumController.text);
          print('新密码：' + newpasswordController.text);
          print('确认密码：' + passwordsureController.text);
          setState(() {
            _buttonClickListen();//监听函数，用于设置按钮的是否可点
          });
          print('生成验证码：' + flag);//将生成的4位随机验证码打印到终端
          Fluttertoast.showToast(msg: '验证码已发送！');
        }
      } else if (newpasswordController.text.isEmpty)
        Fluttertoast.showToast(msg: '请输入新密码！');
      else
        Fluttertoast.showToast(msg: '请确认新密码！');
    } else
      Fluttertoast.showToast(msg: '用户名不存在!');
  }

  void _buttonClickListen() {
    setState(() {
      if (isButtonEnable) {
        //当按钮可点击时
        isButtonEnable = false; //按钮状态标记
        _initTimer();
        flag = _randomBit(4);
      } //当按钮不可点击时
      return null; //返回null按钮禁止点击
    });
  }

  String _randomBit(int len) {
    //设定随机len长度的数作为验证码
    String scope = '0123456789';
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 0) {
        result = scope[Random().nextInt(scope.length)];
      } else {
        result = result + scope[Random().nextInt(scope.length)];
      }
    }
    return result;
  }

  void _initTimer() {
    timer = new Timer.periodic(Duration(seconds: 1), (Timer timer) {
      //设置步长为1s的计时器
      time--;
      setState(() {
        //用于动态改变
        if (time == 0) {
          timer.cancel(); //倒计时结束取消定时器
          time = 60; //重置时间
          isButtonEnable = true; //设置按钮为可按
          buttonText = '发送验证码'; //重置按钮文本
        } else {
          buttonText = '${time}S'; //更新文本内容
        }
      });
    });
  }

  Widget build(BuildContext context) {
    return InkWell(
      //使按钮可按
      onTap: () {
        if (phonenumController.text.length == 11 && isButtonEnable == true) {
          String username = phonenumController.text;
          _check(username, context);
        } else {
          if (isButtonEnable == true) {
            if (phonenumController.text.isEmpty)
              Fluttertoast.showToast(msg: '请输入手机号！');
            else if (phonenumController.text.length != 11)
              Fluttertoast.showToast(msg: '请输入正确的手机号！');
          }
        }
      },
      child: Container(
          height: 50.0,
          width: 130.0,
          padding: EdgeInsets.fromLTRB(15, 0, 8, 2),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(50),
            color: Colors.blue,
          ),
          alignment: Alignment.center,
          child: Text(
            buttonText,
            textAlign: TextAlign.center,
            style: TextStyle( color: Colors.white),
          )),
    );
  }

  void dispose() {
    timer?.cancel(); //销毁计时器
    timer = null;
    TimeController.dispose();
    super.dispose();
  }
}

//修改密码按钮
class ChangeButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        if (phonenumController.text.length == 11 &&
            newpasswordController.text.isNotEmpty &&
            passwordsureController.text.isNotEmpty &&
            verificationController.text.isNotEmpty) {
          if (newpasswordController.text != passwordsureController.text)
            Fluttertoast.showToast(msg: '两次输入的密码不一致！');
          if (verificationController.text == flag) {
            String username = phonenumController.text;
            String password = newpasswordController.text;
            print('点击了修改密码！');
            print('用户名：' + phonenumController.text);
            print('新密码：' + newpasswordController.text);
            print('确认密码：' + newpasswordController.text);
            _update(username, password, context);
          } else {
            Fluttertoast.showToast(msg: '验证码错误！');
          }
        } else {
          if (phonenumController.text.isEmpty)
            Fluttertoast.showToast(msg: '请输入手机号！');
          else if (phonenumController.text.length != 11)
            Fluttertoast.showToast(msg: '请输入正确的手机号！');
          else if (newpasswordController.text.isEmpty)
            Fluttertoast.showToast(msg: '请输入新密码！');
          else if (passwordsureController.text.isEmpty)
            Fluttertoast.showToast(msg: '请确认新密码！');
          else
            Fluttertoast.showToast(msg: '请输入验证码！');
        }
      },
      child: Container(
          width: 300.0,
          padding: EdgeInsets.fromLTRB(2, 10, 2, 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(50),
            color: Colors.green,
          ),
          alignment: Alignment.center,
          child: Text(
            '修改密码',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 20.0, color: Colors.white),
          )),
    );
  }
}

//更新密码函数
_update(String username, String password, BuildContext context) async {
  var url = Uri.parse(Api.url + '/user/check?username=' + username);
  var response = await http.post(url);
  print('Response body: ${response.body}');
  if (response.body == '1') {
    url = Uri.parse(Api.url + '/user/update');
    response = await http.post(url,
        headers: {"content-type": "application/json"},
        body: '{"username": "${username}", "password": "' +
            Api.md5(password) +
            '"}');
    print('Response body: ${response.body}');
    Fluttertoast.showToast(msg: '修改成功!');
  } else
    Fluttertoast.showToast(msg: '用户名不存在!');
}
